'use strict'

import { app, BrowserWindow, Menu, ipcMain, Tray, nativeImage } from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
let appIcon = null
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

const menus = [
  {
    title: '显示主窗口',
    contents: 'showMainWindow'
  },
  {
    title: '退出',
    contents: 'quit'
  }
]

function sendMessage (operate) {
  mainWindow.webContents.send(operate.action, operate)
}

function operateMenu (operate) {
  // 使用 webContents API 向浏览器窗口发送数据来显示笔记内容
  // mainWindow.webContents.send('displayNote', operate)
  if (operate.contents === 'showMainWindow' && mainWindow) {
    console.info('显示主页面1')
    mainWindow.show()
    let focus = {
      action: 'searchFocus',
      contents: '获取光标'
    }
    sendMessage(focus)
  }

  if (operate.contents === 'quit' && mainWindow) {
    mainWindow.close()
  }
}

function addNoteToMenu (operate) {
  return {
    label: operate.title,
    type: 'normal',
    click: () => {
      operateMenu(operate)
    }
  }
}

function createWindow () {
  // var fs = require('fs')
  //
  // if (!fs.existsSync(require('path').join(process.cwd(), '../logo.png'))) {
  //   let readStream = fs.createReadStream('static/logo.png')
  //   let writeStream = fs.createWriteStream('static/logo.png')
  //   readStream.pipe(writeStream)
  // }
  // readStream.close()
  // 创建一个带图标的托盘应用
  appIcon = new Tray(nativeImage.createFromPath(require('path').join(__dirname, 'static/icon.png')))

  // 为托盘应用创建上下文菜单，对笔记进行迭代并添加为菜单项
  let contextMenu = Menu.buildFromTemplate(menus.map(addNoteToMenu))
  appIcon.setToolTip('Notes app')

  // 将上下文菜单绑定到托盘应用上
  appIcon.setContextMenu(contextMenu)

  appIcon.on('click', function (Event) {
    console.info('点击了托盘')
    mainWindow.show()
    let focus = {
      action: 'searchFocus',
      contents: '获取光标'
    }
    sendMessage(focus)

    let logo = {
      action: 'logoRootPath',
      contents: __dirname
    }
    sendMessage(logo)

    let menu = {
      action: 'initPageMenu',
      contents: __dirname
    }
    sendMessage(menu)
  })

  //  双击
  appIcon.on('double-click', () => {
    mainWindow.show()
    let focus = {
      action: 'searchFocus',
      contents: '获取光标'
    }
    sendMessage(focus)
  })
  // 隐藏菜单栏
  Menu.setApplicationMenu(null)
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    frame: false,
    height: 663,
    useContentSize: true,
    width: 1000,
    // skipTaskbar: true,
    webPreferences: {
      nodeIntegration: true, // 解决require is not defined问题
      webviewTag: true, // 解决webview无法显示问题
      webSecurity: false
    }
  })

  mainWindow.loadURL(winURL)

  try {
    const fs = require('fs')
    const devFlag = fs.readFileSync(require('path').join(process.cwd(), '../dev_flag'), 'utf-8')
    // 等待操作结果返回，然后打印结果
    console.log('dev_flag', devFlag)
    if (devFlag === 'yes') {
      // 开发环境
      mainWindow.webContents.openDevTools()
    }
  } catch (e) {
    console.log('读取文件发生错误')
  }
  mainWindow.on('closed', () => {
    mainWindow = null
  })
  // let focus = {
  //   action: 'searchFocus',
  //   contents: '获取光标'
  // }
  // setTimeout(function () {
  //   sendMessage(focus)
  // }, 2000)
}

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  console.info('系统不是单例了，应用退出')
  app.quit()
} else {
  console.info('系统是单例，获取应用')
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      mainWindow.show()
    }
  })
  app.on('ready', createWindow)
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
  let focus = {
    action: 'searchFocus',
    contents: '获取光标'
  }
  sendMessage(focus)
})
app.on('browser-window-blur', () => {
  let focus = {
    action: 'searchFocus',
    contents: '获取光标'
  }
  console.info('后台获取光标')
  sendMessage(focus)
})

// ipcMain.on('close', e => mainWindow.close())
ipcMain.on('close', e => mainWindow.hide())
ipcMain.on('min', e => mainWindow.minimize())

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
